<?php
namespace app\wap\controller;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use app\api\controller\Viator;
use app\admin\controller\Order;
use app\api\model\Fareharbor;
use think\log;
use app\api\controller\KbxOrder as KbxOrder;
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

//初始化日志

class Notify extends Controller
{
    //private $api_url='https://n.kuaibangxing.com/api';
    private $api_url='https://d.kwibon.cn/api';//测试地址

    public $statusArr = array(
        '1' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'pending',
        ),
        '2' => array(
//            'orderStatus' => 'toBeStarting',
            'orderStatus' => 'pending',
            'paymentStatus' => 'paid',
        ),
        '3' => array(
            'orderStatus' => 'finished',
            'paymentStatus' => 'paid',
        ),
        '4' => array(
            'orderStatus' => 'reviewed',
            'paymentStatus' => 'paid',
        ),
        '5' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'refunding',
        ),
        '6' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunding',
        ),
        '7' => array(
            'orderStatus' => 'expired',
            'paymentStatus' => 'pending',
        ),
        '8' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunded',
        ),
        '9' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'rejected',
        ),
        '10' => array(
            'orderStatus' => 'unknown',
            'paymentStatus' => 'pending',
        )
    );

    public function _initialize()
    {
        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    //成功回调
    public function notify()
    {
        $jsonxm2=  file_get_contents("php://input");
        $result=$this->FromXml($jsonxm2);


        $log[]=[
            '微信支付回调'=>json_encode($result),
        ];
        Log::record($log);

        //模拟支付数据
        $result = [
            'return_code'=>'SUCCESS',
            'result_code'=>'SUCCESS',
            'out_trade_no'=>'T10863',
            'openid'=>'o6m8qxMjQ4kB3SjdDK635b59cnR0',
            'total_fee'=>1,
            'time_end'=>time()
        ];
        $KbxOrder = new KbxOrder();
        if ($result){
            //如果成功返回了
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

                $resXml = '<xml>'."<return_code><![CDATA[SUCCESS]]></return_code>"
                    ."<return_msg><![CDATA[OK]]></return_msg>" . "</xml> ";

                $arr['out_trade_no']= explode('KBX',$result['out_trade_no'])[0];
                if (!$arr['out_trade_no']){
                    return false;
                }
                //判断是否为保存在mysql库的订单
                $order=Db::name('order') ->where(['order_no' => $arr['out_trade_no']])->find();

                $total_num_add=0;
                if(!empty($order)){//mysql
                    $order=Db::name('order') ->where(['order_no' => $arr['out_trade_no']])->find();
                    $goods_id=$order['goods_id'];
                    $total_num_add=$order['totalnum'];
                    if ($order['order_status']>=2 && $order['order_status']!==7){
                        return false;
                    }
                    Db::startTrans();
                    try {
                        $time=time();
                        $use = Db::name('member')->where(['wechat_openid' => $result['openid']])->field('member_id')->find();
                        $total_fee = $result['total_fee'] / 100;
                        Db::name('order')
                            ->where(['order_no' => $arr['out_trade_no']])
                            ->update(['order_status' => 2,'updatetime'=>$time]);
                        Db::name('accounts')
                            ->insert([
                                'member_id' => $use['member_id'],
                                'admin_id' => 1,
                                'order_no' => $arr['out_trade_no'],
                                'pay_order_no' => $result['out_trade_no'],
                                'accounts_money' => $total_fee,
                                'business_way' => 1,
                                'creattime' => $result['time_end']
                            ]);
                        Db::commit();
                    }catch (\PDOException $e) {
                        Db::rollback();
                        return $e->getMessage();
                    }

                    //成功下单通知
                    $this->gyouxiang($order);
                    $this->youxiang($order);
                    // 不需要二次确认的  发送凭证修改状态
                    if($order['speedstatus']==0){
                        $this->duanxin($order);
                    }
                }else{
                    //是否定制行程
                    $order = db('custom_made_order')
                        ->where(['order_no'=>$arr['out_trade_no']])
                        ->find();
                    if(!empty($order)){
                        //行程定制
                        $orderType = "CustomMade";
                        if ($order['order_status']>=2 && $order['order_status']!==7){
                            return false;
                        }
                        Db::startTrans();
                        try {
                            $time=time();
                            $use = Db::name('member')
                                ->where(['wechat_openid' => $result['openid']])
                                ->field('member_id')
                                ->find();
                            $total_fee = $result['total_fee'] / 100;
                            Db::name('order')
                                ->where(['order_no' => $arr['out_trade_no']])
                                ->update(['order_status' => 2,'updatetime'=>$time]);
                            Db::name('accounts')
                                ->insert([
                                    'member_id' => $use['member_id'],
                                    'admin_id' => 1,
                                    'order_no' => $arr['out_trade_no'],
                                    'pay_order_no' => $result['out_trade_no'],
                                    'accounts_money' => $total_fee,
                                    'business_way' => 1,
                                    'creattime' => $result['time_end']
                                ]);
                            //更新订单状态
                            $kbx_res = $this->updateCustomMadeOrderStatus($order,1);
                            if(is_array($kbx_res)){
                                Db::commit();
                            }else{
                                Db::rollback();
                                return "更新状态失败,".$kbx_res;
                            }
                        }catch (\PDOException $e) {
                            Db::rollback();
                            return $e->getMessage();
                        }

                    }else{
                    //mongo
                    $kbx_order = $KbxOrder->kbx_order_by_no($arr['out_trade_no']);
                    $orderType = $kbx_order['orderType'];
                    if($orderType!="CarPool"){
                        $goods_id=$kbx_order['goods']['goodsId'];
                        $total_num_add=$kbx_order['goods']['totalnum'];
                    }else{
                        $kbx_order['id'] = $kbx_order['id']??$kbx_order['_id'];
                    }

                    //判断状态
                    $orderStatus = $kbx_order['status']['orderStatus'];
                    $paymentStatus = $kbx_order['status']['paymentStatus'];
                    $order_status= 1;
                    if($orderStatus=='pending'){
                        if($paymentStatus=='pending'){
                            $order_status= 1;//待付款
                        }elseif($paymentStatus=='paid'){
                            $order_status= 2;//已付款待使用
                        }elseif($paymentStatus=='refunding'){
                            $order_status= 5;//退款申请中
                        }elseif($paymentStatus=='rejected'){
                            $order_status= 9;//拒绝退款
                        }
                    }elseif($orderStatus=='toBeStarting'){//待付款
                        if($paymentStatus=='paid'){
                            $order_status= 2;//已付款待使用
                        }elseif($paymentStatus=='refunding'){
                            $order_status= 5;//退款申请中
                        }elseif($paymentStatus=='rejected'){
                            $order_status= 9;//拒绝退款
                        }
                    }elseif($orderStatus=='reviewed'){//已评价
                        $order_status= 4;
                    }elseif($orderStatus=='finished'){//已使用待评价
                        $order_status= 3;
                    }elseif($orderStatus=='canceled'){//已取消
                        if($paymentStatus=='refunded'){
                            $order_status= 8;//已退款
                        }else{
                            $order_status= 6;
                        }
                    }elseif($orderStatus=='expired'){//已过期
                        $order_status= 7;
                    }elseif($orderStatus=='unknown'){//下单失败
                        $order_status= 10;
                    }

                    if ($order_status>=2 && $order_status!==7){
                        return false;
                    }

                    Db::startTrans();
                    try {
                        $time=time();
                        $use = Db::name('member')->where(['wechat_openid' => $result['openid']])->field('member_id')->find();
                        $total_fee = $result['total_fee'] / 100;
                        //订单系统  更新order数据
                        $postUpdateArr = [
                            'id'=>$kbx_order['id'],
                            'payType' => 1,//微信支付
                            'statusPhp'=>array(
                                'orderStatus'=>2,
                            ),
                            'status'=>array(//状态（新）
                                'orderStatus'=>$this->statusArr[2]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[2]['paymentStatus'],
                            ),
                        ];
                        //拼团订单 更新支付状态
                        if($orderType=="CarPool"){
                            $postUpdateArr = [
                                "carPoolOrderId"=>$kbx_order['carPoolOrder']['_id'],
                                "personalCarPoolOrderId"=>$kbx_order['_id'],
                                'payType' => 1,//微信支付
                            ];
                        }
                        $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                        $log[]=[
                            '订单系统API：订单支付成功-微信'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);

                        Db::name('accounts')
                            ->insert([
                                'member_id' => $use['member_id'],
                                'admin_id' => 1,
                                'order_no' => $arr['out_trade_no'],
                                'accounts_money' => $total_fee,
                                'business_way' => 1,
                                'creattime' => $result['time_end']
                            ]);
                        //如果是拼团订单需要增加拼团线路的销量
                        if(isset($kbx_order['carPoolOrder']['line']) && $line_id = $kbx_order['carPoolOrder']['line']){
                            Db::name("group_tours_line")->where(['line_id'=>$line_id])->setInc("sold_num");
                        }
                        Db::commit();
                    }catch (\PDOException $e) {
                        Db::rollback();
                        return $e->getMessage();
                    }

                    //Viator下单
                    if(isset($kbx_order['typeSource']) && $kbx_order['typeSource']=='viator'){
                        $order_info=$kbx_order['itinerary']['orderSubsidiary'];
                        $Viator=new Viator();
                        $order_info=$Viator->object_array($order_info);

                        //预约问题
                        $order_question = '';
                        if(!empty($kbx_order['details']['bookingQuestionAnswers'])){
                            $order_question=$kbx_order['details']['bookingQuestionAnswers'];
                            $order_question = json_decode($order_question,true);
                            $order_question=$Viator->object_array($order_question);
                        }
                        $dat= $Viator->bookingUser($order_info,$order_question,$kbx_order['id'],$kbx_order['orderType']);
                        if ($dat['code']==001){
                            //下单失败
                            // 退款
                            $Orderuser=new Order();
                            $aa= $Orderuser->WxRefund($arr['out_trade_no'].'KBX1230967564',$kbx_order['payments']['foldMoney'],$kbx_order['payments']['foldMoney']);
                            //优惠券退回
                            $cost_ticket_id = isset($kbx_order['payments']['cost_ticket_id']) ? $kbx_order['payments']['cost_ticket_id'] : '';
                            $coupon_type = isset($kbx_order['payments']['coupon_type']) ? $kbx_order['payments']['coupon_type'] : '';
                            if ($coupon_type=='KBX'){
                                if ($cost_ticket_id!==''){
                                    $Kbxcoupon=  new Kbxcoupon();
                                    $d= $Kbxcoupon->refundCashCoupon($use['member_id'],$cost_ticket_id,$kbx_order['orderNo']);
                                }
                            }elseif($coupon_type=='OWN'){
                                db('coupondetails')->where('id',$cost_ticket_id)->update(['usestatus'=>0]);
                            }

                            if ($aa===true){
                                //订单系统  更新order数据
                                $postUpdateArr = [
                                    'id'=>$kbx_order['id'],
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(//状态（新）
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $KbxOrder = new KbxOrder();
                                $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);

                                $log[]=[
                                    '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                    'res'=>$update_res
                                ];
                                Log::record($log);

                                if($update_res){
                                    $md=Db::name('Accounts')->insert([
                                        'member_id'=>$kbx_order['booker']['memberId'],
                                        'order_no'=>$kbx_order['orderNo'],
                                        'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                }
                            }else{
                                $title='自动退款失败';
                                $res='订单号为'.$kbx_order['orderNo'].'的订单，退款失败，原因为'.$aa.'请尽快处理！';
                                $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                            }
                            $title='下单失败';
                            $res='订单号为'.$order['order_no'].'的订单，下单失败，原因为'.json_decode($dat['msg']).'请尽快处理！';
                            $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                            // 下单 失败短信通知
                            $title='预约失败';
                            $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的微信账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                            $this->kbxemailcode($title,$res,$kbx_order['contact']['email']);
                            die;
                        }

                    }elseif(isset($kbx_order['typeSource']) && $kbx_order['typeSource']=='fareharbor'){//fareharbor订单
                        $Fareharbor = new Fareharbor();
                        $goods = db("goods")->where("goods_id",$goods_id)->field("source_id")->find();
                        $fare_goods = db('fareharbor_goods')->where('fare_goods_id',$goods['source_id'])->find();

                        $orderPerson = $kbx_order['itinerary']['orderPerson'];

                        $customerArr = [];
                        foreach ($orderPerson as $k=>$v) {
                            for($i=0;$i<=$v['person_num'];$i++){
                                $customerArr[] = ['customer_type_rate'=>intval($v['person_id'])];
                            }
                        }

                        $params = [
                            'voucher_number'=>$kbx_order['orderNo'],
                            'userinfo'=>[
                                'name'=>$kbx_order['contact']['name'],
                                'phone'=>$kbx_order['contact']['phone'],
                                'email'=>$kbx_order['contact']['email'],
                            ],
                            'customers'=>$customerArr,
                        ];

                        //真实下单
                        $booking_data = $Fareharbor->bookings($fare_goods['company'],$kbx_order['specsId'],$params);
                        if(!empty($booking_data['error'])){
                            //预订失败
                            // 退款
                            $Orderuser=new Order();
                            $aa= $Orderuser->WxRefund($arr['out_trade_no'].'KBX1230967564',$kbx_order['payments']['foldMoney'],$kbx_order['payments']['foldMoney']);
                            //优惠券退回
                            $cost_ticket_id = isset($kbx_order['payments']['cost_ticket_id']) ? $kbx_order['payments']['cost_ticket_id'] : '';
                            $coupon_type = isset($kbx_order['payments']['coupon_type']) ? $kbx_order['payments']['coupon_type'] : '';
                            if ($coupon_type=='KBX'){
                                if ($cost_ticket_id!==''){
                                    $Kbxcoupon=  new Kbxcoupon();
                                    $d= $Kbxcoupon->refundCashCoupon($use['member_id'],$cost_ticket_id,$kbx_order['orderNo']);
                                }
                            }elseif($coupon_type=='OWN'){
                                db('coupondetails')->where('id',$cost_ticket_id)->update(['usestatus'=>0]);
                            }

                            if ($aa===true){
                                //订单系统  更新order数据
                                $postUpdateArr = [
                                    'id'=>$kbx_order['id'],
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(//状态（新）
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $KbxOrder = new KbxOrder();
                                $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);

                                $log[]=[
                                    '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                    'res'=>$update_res,
                                    'error'=>$booking_data['error']
                                ];
                                Log::record($log);

                                if($update_res){
                                    Db::name('Accounts')->insert([
                                        'member_id'=>$kbx_order['booker']['memberId'],
                                        'order_no'=>$kbx_order['orderNo'],
                                        'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                }
                            }else{
                                $title='自动退款失败';
                                $res='订单号为'.$kbx_order['orderNo'].'的订单，退款失败，原因为'.$aa.'请尽快处理！';
                                $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                            }
                            $title='下单失败';
                            $res='订单号为'.$order['order_no'].'的订单，下单失败，原因为'.$booking_data['error'].'请尽快处理！';
                            $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                            // 下单 失败短信通知
                            $title='预约失败';
                            $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的微信账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                            $this->kbxemailcode($title,$res,$kbx_order['contact']['email']);
                            die;

                        }else{
                            //下单成功
                            $postUpdateArr = [
                                'id'=>$kbx_order['id'],
                                'details'=>$booking_data['booking'],
                                'supplier'=>array(
                                    'cost'=>array(
                                        'currency'=>'USD',
                                        'amount'=>$booking_data['booking']['amount_paid']/100
                                    )
                                ),
                                'detailsFrom'=>'fareharbor',
                            ];
                            $KbxOrder = new KbxOrder();
                            $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);

                            $log[]=[
                                '订单系统API：fareharbor下单数据更新'=>json_encode($postUpdateArr),
                                'res'=>$update_res
                            ];
                            Log::record($log);
                        }
                    }

                    if($orderType=="CarPool"){
                        $orderDate = array(
                            'line_id'=>$kbx_order['carPoolOrder']['line'],
                            'member_id'=>$kbx_order['booker']['memberId'],
                            'order_no'=>$kbx_order['orderNo'],
                            'e_mail'=>$kbx_order['customer']['email'],
                            'phone'=>$kbx_order['customer']['username'],
                            "travel_date"=>$kbx_order['carPoolOrder']['details']['startDate'],
                        );
                    }else{
                        $orderDate = array(
                            'goods_id'=>$kbx_order['goods']['goodsId'],
                            'speedstatus'=>$kbx_order['speedStatus'],
                            'member_id'=>$kbx_order['booker']['memberId'],
                            'order_no'=>$kbx_order['orderNo'],
                            'travel_date'=>date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate'])),
                            'e_mail'=>$kbx_order['contact']['email'],
                            'phone'=>$kbx_order['contact']['phone']
                        );
                    }
                    //成功下单通知
                    $this->gyouxiang($orderDate,$orderType,'新小V拼游订单通知【已支付】');
                    $this->youxiang($orderDate,$orderType);
                    // 不需要二次确认的  发送凭证修改状态
                    if(isset($kbx_order['speedStatus']) && $kbx_order['speedStatus']==0){
                        $this->duanxin($orderDate);
                        if($kbx_order['typeSource']=='viator'){
                            $title=$kbx_order['orderNo'];
                            $voucherUrl = "<p><b><a href='https://prelive.viatorapi.viator.com/service/merchant/voucher.jspa?code=".$dat['data']['voucherKey']."&embedResources=false'>点击下载凭证</a></b></p><br>";
                            $this->kbxemailcode($title,$voucherUrl,'david@kuaibangxing.com');
                        }
                    }
                }
                }
                if($orderType!="CarPool"){
                    //更新销量
                    $goodssales=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['goodssales'];
                    $goodssales=(int)$goodssales + $total_num_add;
                    Db::name('goods')->where(['goods_id'=>$goods_id])->update(['goodssales'=>$goodssales]);
                }
                echo $resXml;die;
            }
        }
    }

    public function FromXml($xml)
    {
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $this->values;
    }

    public function kbxorder($kbx_id=''){
        $id= $kbx_id;
        $token = 'Bearer '.$this->kbxToken();
        $url=$this->api_url.'/client/users/'.$id.'/projects';
        $da= $this->get_data($url,$token);
        if (!empty($da)){
            $data=[];
            $dat=[];
            foreach ($da as $k=>$v){
                $data['order_no']=$v['_id'];
                $data['goods_name']=$v['details']['fromCity']['name'].$v['typeStr'];
                $data['travel_date']=date('Y-m-d',strtotime($v['details']['time']));
                $data['remarks']=$v['details']['note'];
                $data['fold_money']=$v['price']['toConsumer'];
                switch($v['displayedStatus']) {
                    //订单状态:1=待付款,2=已付款待使用,3=已使用待评价,4=已评价,5=退款申请中,6=已取消,7=已过期,8=已退款,9=拒绝退款
                    case 'reviewed': $data['order_status']= 4;
                        break;//return '已评价';
                    case 'toBeReviewed': $data['order_status']= 3;
                        break;//return '待评价';
                    case 'refunding':$data['order_status']= 5;
                        break;// return '退款中';
                    case 'refunded': $data['order_status']= 8;
                        break;//return '已退款';
                    case 'canceled': $data['order_status']= 6;
                        break;//return '已取消';
                    case 'pending':$data['order_status']= 1;
                        break;// return '待付款';
                    case 'progressing':$data['order_status']= 2;
                        break;// return '进行中';
                    default: return '';
                }

                if (!empty( $v['details']['adultPassengers'])){
                    $data['person'][]=[
                        'person_num'=>$v['details']['adultPassengers'],
                        'person_name'=>'成年乘客',
                    ];
                }
                if (!empty( $v['details']['childPassengers'])){
                    $data['person'][]=[
                        'person_num'=>$v['details']['childPassengers'],
                        'person_name'=>'儿童乘客',
                    ];
                }
                if ($data['order_status']==1){
                    $kbx_url=config('kbx_url');
                    $data['url']=$kbx_url.'/2cstatic/#/affirm-order?orderId='.$v['_id'];
                }

                $data['types']='KBX';

                $dat[]=$data;
                $data=[] ;
            }
        }

        return $dat;
    }

    public function gyouxiang($order,$orderType="",$subject=""){

        $member=db('member')->where('member_id',$order['member_id'])->find();
        $subject=empty($subject)?'新订单通知【测试】':$subject;
        $address='david@kuaibangxing.com';
        //subject: 邮件标题（必填）
        //content: 邮件正文（必填）
        //address: 邮件接收地址，多个地址以逗号分隔（必填）
        if($orderType=="CustomMade"){
            //定制行程后 邮件通知
            $content = $member['member_nickname']."用户于 ".date('Y-m-d H:i:s',time());
            $content .= " 购买的定制行程 <a>".$order['tripname'] ."</a>已预订成功，
 ";
            $content .= "订单号<a> ".$order['order_no'] ."</a>  。";
            $content .= "可进入<a href='https://c.kuaibangxing.com/admin/common/login'>快帮行</a>后台系统确认";

        }elseif($orderType=="carPool"){
            $datas= db('group_tours_line')->alias('a')
                ->where('a.line_id',$order['line_id'])
                ->join('city b','b.id=a.city_id')
                ->field('a.title as goods_name,b.name')
                ->find();
            $content = $member['member_nickname']."用户于 ".date('Y-m-d H:i:s',time());
            $content .= " 购买的商品 <a>".$datas['name'] ."</a> 的<a> ".$datas['goods_name'] ."</a>已预订成功，
 ";
            $content .= "订单号<a> ".$order['order_no'] ."</a>  。";
            $content .= "可进入<a href='https://c.kuaibangxing.com/admin/common/login'>快帮行</a>后台系统确认";

        }else{
            $datas= db('goods')->alias('a')
                ->where('a.goods_id',$order['goods_id'])
                ->join('city b','b.id=a.city_id')
                ->field('a.goods_name,b.name')
                ->find();
            $content  = $member['member_nickname']."用户于 ".date('Y-m-d H:i:s',time());
            $content .= " 购买的商品 <a>".$datas['name'] ."</a> 的<a> ".$datas['goods_name'] ."</a>已预订成功，
 ";
            $content .= "订单号<a> ".$order['order_no'] ."</a>  。";
            $content .= "可进入<a href='https://c.kuaibangxing.com/admin/common/login'>快帮行</a>后台系统确认";
        }
        $d = $this->kbxemailcode($subject,$content,$address);
    }

    public function youxiang($order,$orderType=""){
        if($orderType=="CarPool"){
            $datas= db('group_tours_line')->alias('a')->where('a.line_id',$order['line_id'])
                ->join('city b','b.id=a.city_id')->field('a.title as goods_name,b.name')
                ->find();
        }else{
            $datas= db('goods')->alias('a')->where('a.goods_id',$order['goods_id'])
                ->join('city b','b.id=a.city_id')->field('a.goods_name,b.name')
                ->find();
        }
        $member=db('member')->where('member_id',$order['member_id'])->find();
        //定制不存在二次确认
        if($orderType=='CustomMade'){//定制行程
            $content= "
        <p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
        <p>    您的订单已预订成功，祝您出行愉快，快帮行与您一路同行。</p>
<p>    定制产品：".$order['tripname']."</p>

<p>    订单号：".$order['order_no'] ."</p>

<p>    出行日期：".$order['travel_date'] ."</p>
 
<p>    您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态，本订单完成之后您将获取   <a href=''style='color:#ff7d00 '> ".(int)$order['add_integral']."</a>积分，预祝您的行程愉快！</p>
<p>    有任何问题，请联系我们</p>

<div style='opacity:1;position: relative;'>
    <p>    * 国内客服: <a>+86 400-100-5295</a></p>
    <p>    * 北美客服: <a>+1 800-932-1178</a></p>
    <p>    * 客服微信：</p>
    <p style='text-align: center;'><img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/xiaomeicode1.jpg'></p>
    <p>      官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
    <p> <img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/kbx_adv1.jpg'> </p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
        ";
        }elseif (isset($order['speedstatus']) && $order['speedstatus']==0){//二次确认
            $content= "
        <p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;您的订单已预订成功，祝您出行愉快，快帮行与您一路同行。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;产品：".$datas['name'] ."下的".$datas['goods_name']."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;订单号：".$order['order_no'] ."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;使用日期：".$order['travel_date'] ."</p>
 
<p>&nbsp;&nbsp;&nbsp;&nbsp;您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态，本订单完成之后您将获取   <a href=''style='color:#ff7d00 '> ".(int)$order['add_integral']."</a>积分，预祝您的行程愉快！</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;有任何问题，请联系我们</p>

<div style='opacity:1;position: relative;'>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 国内客服: <a>+86 400-100-5295</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 北美客服: <a>+1 800-932-1178</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 客服微信：</p>
    <p style='text-align: center;'><img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/xiaomeicode1.jpg'></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;  官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
    <p> <img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/kbx_adv1.jpg'> </p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
        ";
        }else{
            $content= "
        
        <p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
                <p>&nbsp;&nbsp;&nbsp;&nbsp;感谢您在快帮行的预订！我们正在处理您的订单，</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;产品：".$datas['name'] ."下的".$datas['goods_name']."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;订单号：".$order['order_no'] ."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;使用日期：".$order['travel_date'] ."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;订单一旦确认，我们将通过邮件告知，您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态。</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;有任何问题，请联系我们</p>
<div style='opacity:1;position: relative;'>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 国内客服: <a>+86 400-100-5295</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 北美客服: <a>+1 800-932-1178</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 客服微信：</p>
    <p style='text-align: center;'><img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/xiaomeicode1.jpg'></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;  官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
    <p> <img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/kbx_adv1.jpg'> </p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
    ";
        }
        if($orderType=="CarPool"){
            $content= "<p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
                <p>感谢您在快帮行的预订！我们正在处理您的订单，</p>

<p>    您购买的拼团产品：".$datas['name'] ."下的".$datas['goods_name']."</p>

<p>    订单号：".$order['order_no'] ."</p>

<p>    请耐心等待业务人员和您确认出行事宜，我们会尽快和你联系！</p>

<p>    订单一旦确认，我们将通过邮件告知，您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态。</p>

<p>    有任何问题，请联系我们</p>
<div style='opacity:1;position: relative;'>
    <p>    * 国内客服: <a>+86 400-100-5295</a></p>
    <p>    * 北美客服: <a>+1 800-932-1178</a></p>
    <p>    * 客服微信：</p>
    <p style='text-align: center;'><img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/xiaomeicode1.jpg'></p>
    <p>      官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
    <p> <img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/kbx_adv1.jpg'> </p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
    ";
        }

        $subject='快帮行商品购买通知【测试】';

        $address=$order['e_mail'].',david@kuaibangxing.com';
        //subject: 邮件标题（必填）
        //content: 邮件正文（必填）
        //address: 邮件接收地址，多个地址以逗号分隔（必填）

        $d = $this->kbxemailcode($subject,$content,$address);

    }

    public function duanxin($order){
        $datas= db('goods')->alias('a')->where('a.goods_id',$order['goods_id'])->join('city b','b.id=a.city_id')->field('a.goods_name,b.name')
            ->find();
        $data=[];
        $data['mobile']=$order['phone'];
        $data['date']=date('Y-m-d H:i:s',time());
        $data['city']=$datas['name'];
        $data['service']=$datas['goods_name'];
        $data['orderId']=$order['order_no'];
        $d=$this->kbxpaysuccess($data);
    }

    //邮箱验证码
    public function kbxemailcode($subject='',$content='',$address=''){
        $url=$this->api_url.'/client/email';
        $list=[];   //post值
        $where=[];  //组装条件
        $token = 'Bearer '.$this->kbxToken();
        if (!empty($subject)&& !empty($content)&&!empty($address)){
            $subject = "【测试】".$subject;
            $list=['subject'=>$subject,'content'=>$content,'address'=>$address];
        }else{
            return '数据错误参数为空';
        }

        $list=json_encode($list);
        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));
        return $content;
    }

    public function kbxpaysuccess($datas=''){
        $url=$this->api_url.'/client/sms/paysuccess';
        $token = 'Bearer '.$this->kbxToken();
        $list=json_encode($datas);

        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));

        return  $content;
    }


    /**
     * 快帮行Token获取
     *
     * @param $clientId 客户端ID，由快帮行后台提前分配
     * @param $secret   根据当前时间生成的时间字符串
     * @param $timeStamp    快帮行后台提供的 秘钥+timeStamp 字符串合并后做MD5加密的结果字符串
     * $clientId='5b4f0a2322437c15382e767d',$secret='kwiBon20l8',$timeStamp=''
     */
    public function kbxToken($clientId='5b4f0a2322437c15382e767d',$secret='kwiBon20l8',$timeStamp=''){
        $url = $this->api_url."/auth/login/client";
        $timeStamp = date("YmdH:i",time());
        $data['clientId'] = $clientId;
        $data['timeStamp'] = $timeStamp;
        $data['secret'] = md5($secret.$data['timeStamp']);
        $data = json_encode($data);
        list($return_code,$headers,$return_content) = $this->http_post_data($url, $data);
        $content = json_decode($return_content,true);

        if($content['token']){
            return $content['token'];
        }else{
            $this->error(__('Server error'), '', -104);
        }
    }

    function get_data($url,$token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json; charset=utf-8",
            'Authorization:'.$token
        ));
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        $output = curl_exec($curl);
        $info = json_decode($output, true);
        return $info;
    }

    function http_post_data($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return array($return_code, $headers,$return_content);
    }

    function post_data($url, $data_string,$token) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                'Authorization:'.$token,
            )
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return $return_content;
    }

    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        }
        if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    //订单系统  信用卡接口
    protected function kbxPayByCredit($datas=''){
        $url=$this->api_url.'/client/ActivityOrder/stripePay';
        $token='Bearer '.$this->kbxToken();
        $list=json_encode($datas);

        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));

        $log[]=[
            'PayByCredit_data'=>$list,
            'PayByCredit_content'=>$content,
        ];
        Log::record($log);

        return $content;
    }

    //订单系统  信用卡  退款接口
    public function kbxCreditRefund($chargeId='',$reason=''){
        $url=$this->api_url.'/client/ActivityOrder/stripeRefund';
        $token='Bearer '.$this->kbxToken();
        $data = array(
            'chargeId' => $chargeId,
            'reason' => $reason
        );
        $list=json_encode($data);

        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));

        $log[]=[
            '信用卡退款ID'=>$list,
            '信用卡退款data'=>$content,
        ];
        Log::record($log);

        return $content;
    }

    //前端调用信用卡支付
    public function payByCredit() {
        header('Access-Control-Allow-Origin:*');
        $post = request()->post();
        if($post['orderType']=='CarPool'){
            $post['order_id'] = 1;
        }
        if(!isset($post['currency']) || !isset($post['order_no']) || !isset($post['stripeToken']) || empty($post['order_id'])){
            $shu=[
                'code'=>401,
                'msg'=>'缺少字段',
            ];
            return json_encode($shu,JSON_UNESCAPED_UNICODE );
        }

        $order_no = trim($post['order_no']);
        $orderType = trim($post['orderType']);
        $order_id = trim($post['order_id']);
        $currency = trim($post['currency']);

        //汇率
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency)->find();
        $exchangeRate = 1;
        if($exchangeArr){
            $exchangeRate = $exchangeArr['exchange_rate'];
        }
        //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
        if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
        { //mysql
            $order = db('order')->where('order_id',$order_id)->find();
            if($order['order_status']!=="1" && $order['order_status']!=="7"){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！status='.$order['order_status'],
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }

            $accounts = db('accounts')->where('order_no',$order['order_no'])->find();
            if(!empty($accounts)){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }

            if($currency=='CNY'){//人民币
                $fold_money = $order['fold_money'];
            }else{
                $fold_money = $order['fold_money']/$exchangeRate;
                $fold_money = ceil($fold_money*100)/100;
            }
            $goods_id = $order['goods_id'];
            $good = db('goods')->where('goods_id',$goods_id)->find();
            if($fold_money>0){
                $list['amount'] = $fold_money;
                $list['currency'] = $post['currency'];
                $list['token'] = $post['stripeToken'];
                $list['orderNo'] = $order['order_no'];
                $list['description'] = "快帮行-电商平台-订单：".$list['orderNo']."-".$good['goods_name']."-信用卡支付：".$currency."  ".$fold_money;
            }else{
                $shu=[
                    'code'=>402,
                    'msg'=>'支付金额不存在',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE ) ;
            }
        } elseif ($orderType=='CustomMade'){//定制行程的支付
            $order = db('custom_made_order')->where('order_no',$order_no)->find();
            if($order['order_status']!=="1" && $order['order_status']!=="7"){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！status='.$order['order_status'],
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }

            $accounts = db('accounts')->where('order_no',$order['order_no'])->find();
            if(!empty($accounts)){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }
            if($order['fold_money']>0){
                $list['amount'] = $order['fold_money'];
                $list['currency'] = "CNY";
                $list['token'] = $post['stripeToken'];
                $list['orderNo'] = $order_no;
                $list['description'] = "快帮行-电商平台-订单：".$list['orderNo']."-信用卡支付：".$currency."  ".$order['fold_money'];
            }else{
                $shu=[
                    'code'=>402,
                    'msg'=>'支付金额不存在',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE ) ;
            }
        } else {//mongo
            $KbxOrder = new KbxOrder();
            $kbx_order = $KbxOrder->kbx_order_by_no($order_no);
            if($kbx_order['status']['orderStatus']!=="pending" && $kbx_order['status']['orderStatus']!=="carpool"){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！status='.$kbx_order['status']['orderStatus'],
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }

            $accounts = db('accounts')->where('order_no',$order_no)->find();
            if(!empty($accounts)){
                $shu=[
                    'code'=>403,
                    'msg'=>'该订单已支付！请转至订单页面查询！',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }

            if($currency=='CNY'){//人民币
                $fold_money = $kbx_order['payments']['foldMoney'];
            }else{
                $fold_money = $kbx_order['payments']['foldMoney']/$exchangeRate;
                $fold_money = ceil($fold_money*100)/100;
            }
            $goods_id = $kbx_order['goods']['goodsId'];
            $good = db('goods')->where('goods_id',$goods_id)->find();
            if($fold_money>0){
                $list['amount'] = $fold_money;
                $list['currency'] = $post['currency'];
                $list['token'] = $post['stripeToken'];
                $list['orderNo'] = $order_no;
                $list['description'] = "快帮行-电商平台-订单：".$list['orderNo']."-".$good['goods_name']."-信用卡支付：".$currency."  ".$fold_money;
            }else{
                $shu=[
                    'code'=>402,
                    'msg'=>'支付金额不存在',
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE ) ;
            }
        }

        if(!empty($list)){
            $res = $this->kbxPayByCredit($list);
            //$res = $this->myPayByCredit($list);
            if($res){
                if(!empty($res['status']) && $res['status']=='succeeded'){
                    $book_res = $this->PayByCreditSuccess($order_no,$res,$orderType);
                    $res_msg = $book_res['msg'];
                    $res_code = $book_res['code'];
                }else{
                    $res_code = 401;
                    $res_msg = $res['msg'];

                    if($res_msg=='Your card has insufficient funds.'){
                        $res_msg = "请求被拒绝，您的信用卡可用余额不足";
                    }elseif($res_msg='Your card was declined.'){
                        $res_msg = "请求被拒绝，请检查余额和开卡状态";
                    }
                }
                $shu=[
                    'code'=>$res_code,
                    'msg'=>$res_msg,
                    'data'=>$res,
                ];
                return json_encode($shu,JSON_UNESCAPED_UNICODE );
            }
        }
    }

    //信用卡支付成功回调
    protected function PayByCreditSuccess($order_no,$credit_data,$orderType)
    {
        $time=time();
        $KbxOrder = new KbxOrder();

        //判断订单类型，决定是否调用订单系统接口，存订单系统mongo库还是本系统mysql
        if(in_array($orderType,array("Vehicle","Custom","Other","Rental_Device","Price_Gap","Self_Drive","Personal_Tailor","Subscription")))
        {//mysql
            Db::startTrans();
            try {
                $order = Db::name('order')->where(['order_no' => $order_no])->find();
                if ($order['order_status']>=2){
                    return false;
                }
                Db::name('order')
                    ->where(['order_no' => $order_no])
                    ->update(['order_status' => 2,'pay_type' => 2,'updatetime'=>$time]);

                Db::name('accounts')
                    ->insert([
                        'member_id' => $order['member_id'],
                        'order_no' => $order['order_no'],
                        'admin_id' => 1,
                        'accounts_money' => $order['fold_money'],
                        'business_way' => 1,
                        'credit_charge_id' => $credit_data['id'],//返回的支付id
                        'credit_charge_data' => json_encode($credit_data,JSON_UNESCAPED_UNICODE),//返回的支付data
                        'creattime' => date('YmdHis',$time)
                    ]);

                //写入销量
                $goods_id=$order['goods_id'];
                $goodssales=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['goodssales'];
                $goodssales=(int)$goodssales + (int)$order['totalnum'];
                Db::name('goods')->where(['goods_id'=>$goods_id])->update(['goodssales'=>$goodssales]);

                Db::commit();
            }catch (\PDOException $e) {
                Db::rollback();
                return array('code'=>402,'msg'=>"数据写入错误".$e->getMessage());
            }

            //成功下单通知
            $this->gyouxiang($order);
            $this->youxiang($order);
            // 不需要二次确认的  发送凭证修改状态
            if($order['speedstatus']==0){
                $this->duanxin($order);
            }
        }elseif($orderType=='CustomMade'){//定制行程自动建单
            Db::startTrans();
            try {
                $custom_order = db("custom_made_order")->where(['order_no' => $order_no])->find();
                if ($custom_order['order_status'] >= 2) {
                    return false;
                }
                //修改支付状态
                Db::name('custom_made_order')
                    ->where(['order_no' => $order_no])
                    ->update(['order_status' => 2,'pay_type' => 2,'updatetime'=>$time]);
                //修改行程订单状态
                Db::name('trip')->where(['id'=>$custom_order['trip_id']])->update(['isPaid'=>1,'isLocked'=>1]);

                db('accounts')
                    ->insert([
                        'member_id' => $custom_order['member_id'],
                        'order_no' => $custom_order['order_no'],
                        'admin_id' => 1,
                        'order_type' => $orderType,
                        'accounts_money' => $custom_order['fold_money'],
                        'business_way' => 1,
                        'credit_charge_id' => $credit_data['id'],//返回的支付id
                        'credit_charge_data' => json_encode($credit_data, JSON_UNESCAPED_UNICODE),//返回的支付data
                        'creattime' => date('YmdHis', $time)
                    ]);
                //更新订单状态
                $kbx_res = $this->updateCustomMadeOrderStatus($custom_order,2);
                if(is_array($kbx_res)){
                    Db::commit();
                }else{
                    Db::rollback();
                    return array('code'=>402,'msg'=>"更新状态失败,".$kbx_res);
                }
            }catch (\PDOException $e) {
                Db::rollback();
                return array('code'=>402,'msg'=>"数据写入错误".$e->getMessage());
            }
            //邮件通知
            $orderDate = array(
                'tripid' => $kbx_res['id'],
                'tripname' => $kbx_res['orderName'],
                'member_id' => $custom_order['member_id'],
                'order_no' => $order_no,
                'e_mail' => $kbx_res['contact']['email'],
                'phone' => $kbx_res['contact']['name'],
                "travel_date" => $kbx_res['startDate'],
            );
            //成功下单通知
            $this->gyouxiang($orderDate,$orderType);
            $this->youxiang($orderDate,$orderType);
            //返回消息
            return [
                'code'=>0,
                'msg'=>'支付成功'
            ];
        }else {//mongo
            Db::startTrans();
            try {
                $kbx_order = $KbxOrder->kbx_order_by_no($order_no);
                //订单系统  更新order数据
                $postUpdateArr = [
                    'id' => $kbx_order['id'],
                    'payType' => 2,//信用卡支付
                    'statusPhp' => array(
                        'orderStatus' => 2,
                    ),
                    'status' => array(
                        'orderStatus' => $this->statusArr[2]['orderStatus'],
                        'paymentStatus' => $this->statusArr[2]['paymentStatus'],
                    ),
                ];
                //拼团订单 更新支付状态
                if($orderType=="CarPool"){
                    $postUpdateArr = [
                        "carPoolOrderId"=>$kbx_order['carPoolOrder']['_id'],
                        "personalCarPoolOrderId"=>$kbx_order['_id'],
                        'payType' => 2,//信用卡支付
                    ];
                }
                $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);
                $log[] = [
                    '订单系统API：订单支付成功-信用卡' => json_encode($postUpdateArr),
                    'res' => $update_res
                ];
                Log::record($log);
                Db::name('accounts')
                    ->insert([
                        'member_id' => $kbx_order['booker']['memberId'],
                        'order_no' => $order_no,
                        'admin_id' => 1,
                        'accounts_money' => $kbx_order['payments']['foldMoney'],
                        'business_way' => 1,
                        'credit_charge_id' => $credit_data['id'],//返回的支付id
                        'credit_charge_data' => json_encode($credit_data, true),//返回的支付data
                        'creattime' => date('YmdHis', $time)
                    ]);
                //如果是拼团订单需要增加拼团线路的销量
                if(isset($kbx_order['carPoolOrder']['line']) && $line_id = $kbx_order['carPoolOrder']['line']){
                    Db::name("group_tours_line")->where(['line_id'=>$line_id])->setInc("sold_num");
                }
                Db::commit();
            } catch (\PDOException $e) {
                Db::rollback();
                return array('code' => 402, 'msg' => "数据写入错误" . $e->getMessage());
            }

            try {
                //Viator下单
                if($kbx_order['typeSource']=='viator'){
                    $order_info=$kbx_order['itinerary']['orderSubsidiary'];
                    $Viator=new Viator();
                    $order_info=$Viator->object_array($order_info);

                    //预约问题
                    $order_question = '';
                    if(!empty($kbx_order['details']['bookingQuestionAnswers'])){
                        $order_question=$kbx_order['details']['bookingQuestionAnswers'];
                        $order_question = json_decode($order_question,true);
                        $order_question=$Viator->object_array($order_question);
                    }
                    $dat= $Viator->bookingUser($order_info,$order_question,$kbx_order['id'],$kbx_order['orderType']);
                    if ($dat['code']==001){
                        //下单失败
                        // 退款
                        $refund_res = $this->kbxCreditRefund($credit_data['id'],"Viator下单失败");
                        //优惠券退回
                        $cost_ticket_id = isset($kbx_order['payments']['cost_ticket_id']) ? $kbx_order['payments']['cost_ticket_id'] : '';
                        $coupon_type = isset($kbx_order['payments']['coupon_type']) ? $kbx_order['payments']['coupon_type'] : '';
                        if ($coupon_type=='KBX'){
                            if ($cost_ticket_id!==''){
                                $Kbxcoupon=  new Kbxcoupon();
                                $d= $Kbxcoupon->refundCashCoupon($kbx_order['booker']['memberId'],$cost_ticket_id,$order_no);
                            }
                        }elseif($coupon_type=='OWN'){
                            db('coupondetails')->where('id',$cost_ticket_id)->update(['usestatus'=>0]);
                        }

                        //订单系统  更新order数据
                        $postUpdateArr = [
                            'id'=>$kbx_order['id'],
                            'statusPhp'=>array(
                                'orderStatus'=>'10',
                            ),
                            'status'=>array(
                                'orderStatus'=>$this->statusArr[10]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[10]['paymentStatus'],
                            ),
                            'specsId'=>'2',
                        ];
                        $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                        $log[]=[
                            '订单系统API：viator预订失败'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);

                        if ($refund_res['status']==='succeeded'){
                            //订单系统  更新order数据
                            $postUpdateArr = [
                                'id'=>$kbx_order['id'],
                                'statusPhp'=>array(
                                    'orderStatus'=>8,
                                ),
                                'status'=>array(
                                    'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                    'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                ),
                                'refund'=>array(
                                    'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                    'refundStatus'=>2,
                                ),
                            ];
                            $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                            $log[]=[
                                '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                'res'=>$update_res
                            ];
                            Log::record($log);

                            if($update_res){
                                Db::name('Accounts')->insert([
                                    'member_id'=>$kbx_order['booker']['memberId'],
                                    'order_no'=>$order_no,
                                    'admin_id' => 1,
                                    'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                    'business_way'=>4,
                                    'description'=>"Viator下单失败",
                                    'credit_charge_id' => $credit_data['id'],//支付id
                                    'credit_charge_data' => json_encode($refund_res,true),//返回的退款data
                                    'creattime'=>date('YmdHis',time())
                                ]);
                            }

                            $res_data['code'] = "403";
                            $res_data['msg'] = "订单预约失败，退款已原路返回，如有疑问请联系国内客服";
                        }else{
                            $title='信用卡自动退款失败';
                            $res='订单号为'.$order_no.'的订单，退款失败，原因为'.$refund_res['msg'].'请尽快处理！';
                            $this->kbxemailcode($title,$res,'david@kuaibangxing.com');

                            $res_data['code'] = "404";
                            $res_data['msg'] = "订单预约失败，自动退款故障，退款请联系国内客服返还";
                        }
                        $title='下单失败';
                        $res='订单号为'.$order_no.'的订单，下单失败，原因为'.$dat['msg'].'请尽快处理！';
                        $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                        // 下单 失败短信通知
                        $title='预约失败';
                        $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的信用卡账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                        $this->kbxemailcode($title,$res,$kbx_order['contact']['email']);

                        return $res_data;
                    }

                }elseif($kbx_order['typeSource']=='fareharbor'){//fareharbor订单
                    $Fareharbor = new Fareharbor();
                    $goods = db("goods")->where("goods_id",$kbx_order['goods']['goodsId'])->field("source_id")->find();
                    $fare_goods = db('fareharbor_goods')->where('fare_goods_id',$goods['source_id'])->find();

                    $orderPerson = $kbx_order['itinerary']['orderPerson'];

                    $customerArr = [];
                    foreach ($orderPerson as $k=>$v) {
                        for($i=0;$i<=$v['person_num'];$i++){
                            $customerArr[] = ['customer_type_rate'=>intval($v['person_id'])];
                        }
                    }

                    $params = [
                        'voucher_number'=>$kbx_order['orderNo'],
                        'userinfo'=>[
                            'name'=>$kbx_order['contact']['name'],
                            'phone'=>$kbx_order['contact']['phone'],
                            'email'=>$kbx_order['contact']['email'],
                        ],
                        'customers'=>$customerArr,
                    ];

                    //真实下单
                    $booking_data = $Fareharbor->bookings($fare_goods['company'],$kbx_order['specsId'],$params);
                    if(!empty($booking_data['error'])){
                        //预订失败
                        // 退款
                        $refund_res = $this->kbxCreditRefund($credit_data['id'],"fareharbor下单失败");
                        //优惠券退回
                        $cost_ticket_id = isset($kbx_order['payments']['cost_ticket_id']) ? $kbx_order['payments']['cost_ticket_id'] : '';
                        $coupon_type = isset($kbx_order['payments']['coupon_type']) ? $kbx_order['payments']['coupon_type'] : '';
                        if ($coupon_type=='KBX'){
                            if ($cost_ticket_id!==''){
                                $Kbxcoupon=  new Kbxcoupon();
                                $d= $Kbxcoupon->refundCashCoupon($kbx_order['booker']['memberId'],$cost_ticket_id,$order_no);
                            }
                        }elseif($coupon_type=='OWN'){
                            db('coupondetails')->where('id',$cost_ticket_id)->update(['usestatus'=>0]);
                        }

                        //订单系统  更新order数据
                        $postUpdateArr = [
                            'id'=>$kbx_order['id'],
                            'statusPhp'=>array(
                                'orderStatus'=>'10',
                            ),
                            'status'=>array(
                                'orderStatus'=>$this->statusArr[10]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[10]['paymentStatus'],
                            ),
                            'specsId'=>'2',
                        ];
                        $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                        $log[]=[
                            '订单系统API：fareharbor预订失败'=>json_encode($postUpdateArr),
                            'res'=>$update_res,
                            'error'=>$booking_data['error']
                        ];
                        Log::record($log);

                        if ($refund_res['status']==='succeeded'){
                            //订单系统  更新order数据
                            $postUpdateArr = [
                                'id'=>$kbx_order['id'],
                                'statusPhp'=>array(
                                    'orderStatus'=>8,
                                ),
                                'status'=>array(
                                    'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                    'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                ),
                                'refund'=>array(
                                    'refundMoney'=>$kbx_order['payments']['foldMoney'],
                                    'refundStatus'=>2,
                                ),
                            ];
                            $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);
                            $log[]=[
                                '订单系统API：退款成功'=>json_encode($postUpdateArr),
                                'res'=>$update_res
                            ];
                            Log::record($log);

                            if($update_res){
                                Db::name('Accounts')->insert([
                                    'member_id'=>$kbx_order['booker']['memberId'],
                                    'order_no'=>$order_no,
                                    'admin_id' => 1,
                                    'accounts_money'=>$kbx_order['payments']['foldMoney'],
                                    'business_way'=>4,
                                    'description'=>"Viator下单失败",
                                    'credit_charge_id' => $credit_data['id'],//支付id
                                    'credit_charge_data' => json_encode($refund_res,true),//返回的退款data
                                    'creattime'=>date('YmdHis',time())
                                ]);
                            }

                            $res_data['code'] = "403";
                            $res_data['msg'] = "订单预约失败，退款已原路返回，如有疑问请联系国内客服";
                        }else{
                            $title='信用卡自动退款失败';
                            $res='订单号为'.$order_no.'的订单，退款失败，原因为'.$refund_res['msg'].'请尽快处理！';
                            $this->kbxemailcode($title,$res,'david@kuaibangxing.com');

                            $res_data['code'] = "404";
                            $res_data['msg'] = "订单预约失败，自动退款故障，退款请联系国内客服返还";
                        }
                        $title='下单失败';
                        $res='订单号为'.$order_no.'的订单，下单失败，原因为'.$booking_data['error'].'请尽快处理！';
                        $this->kbxemailcode($title,$res,'david@kuaibangxing.com');
                        // 下单 失败短信通知
                        $title='预约失败';
                        $res='【快帮行】您好，您的订单预订失败，退款已原路返回您的信用卡账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                        $this->kbxemailcode($title,$res,$kbx_order['contact']['email']);

                        return $res_data;

                    }else{
                        //下单成功
                        $postUpdateArr = [
                            'id'=>$kbx_order['id'],
                            'details'=>$booking_data['booking'],
                            'supplier'=>array(
                                'cost'=>array(
                                    'currency'=>'USD',
                                    'amount'=>$booking_data['booking']['amount_paid']/100
                                )
                            ),
                            'detailsFrom'=>'fareharbor',
                        ];
                        $KbxOrder = new KbxOrder();
                        $update_res = $KbxOrder->kbx_operate_order($kbx_order['orderType'],$postUpdateArr);

                        $log[]=[
                            '订单系统API：fareharbor下单数据更新'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);
                    }
                }

            }catch (\PDOException $e) {
                $log_error[]=[
                    '订单系统API：第三方'.$kbx_order['typeSource'].'订单预订失败-信用卡付款' => $e->getMessage(),
                ];
                Log::record($log_error);

                return $e->getMessage();
            }


            //写入销量  销量不按单统计，按购买的数量
            $goods_id=$kbx_order['goods']['goodsId'];
            $goodssales=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['goodssales'];
            $goodssales=(int)$goodssales + (int)$kbx_order['goods']['totalnum'];
            Db::name('goods')->where(['goods_id'=>$goods_id])->update(['goodssales'=>$goodssales]);

            $orderDate = array(
                'goods_id'=>$kbx_order['goods']['goodsId'],
                'speedstatus'=>$kbx_order['speedStatus'],
                'member_id'=>$kbx_order['booker']['memberId'],
                'order_no'=>$order_no,
                'travel_date'=>date('Y-m-d',strtotime($kbx_order['itinerary']['travelDate'])),
                'e_mail'=>$kbx_order['contact']['email'],
                'phone'=>$kbx_order['contact']['phone']
            );
            if($orderType=="CarPool"){
                $orderDate = array(
                    'line_id'=>$kbx_order['carPoolOrder']['line'],
                    'member_id'=>$kbx_order['booker']['memberId'],
                    'order_no'=>$order_no,
                    'e_mail'=>$kbx_order['user']['email'],
                    'phone'=>$kbx_order['user']['username'],
                    "travel_date"=>$kbx_order['carPoolOrder']['details']['startDate'],
                );
            }
            //成功下单通知
            $this->gyouxiang($orderDate,$orderType);
            $this->youxiang($orderDate,$orderType);
            // 不需要二次确认的  发送凭证修改状态
            if($kbx_order['speedStatus']==0){
                $this->duanxin($orderDate);
                if($kbx_order['typeSource']=='viator'){
                    $title=$order_no;
                    $voucherUrl = "<p><b><a href='https://prelive.viatorapi.viator.com/service/merchant/voucher.jspa?code=".$dat['data']['voucherKey']."&embedResources=false'>点击下载凭证</a></b></p><br>";
                    $this->kbxemailcode($title,$voucherUrl,'david@kuaibangxing.com');
                }
            }
        }

        $res_data['code'] = "0";
        $res_data['msg'] = "支付成功";

        return $res_data;
    }

    //行程订单的成功回调
    protected function paySuccessTripOrder($trip_id,$wx_result_data)
    {
        //查询行程信息
        $trip = db("trip")->find($trip_id);
        if(!epmty($trip)){
            $KbxOrder = new KbxOrder();
            $data['_id']=$trip['opportunity_id'];
            $data['paid']=true;
            //支付数据有待封装
            $data['payment']=$wx_result_data;
            //调用订单系统去自动建单
            $res = $KbxOrder->enterBusOpportunities($data);

            if($res!==""){
                return true;
            }else{
                return false;
            }
        }
    }

    //定制形成支付完成修改订单状态
    public function updateCustomMadeOrderStatus($order,$payType)
    {
        //获取下单数据
        $trip = json_decode($order['orderSnap'],true);
        //推送订单状态 pushCustomOrderPaySuccess ...
        $kbx_res = (new KbxOrder())->updatePaidCustomOrder(['_id'=>$order['kbx_id'],'payType'=>$payType,'adminId'=>-1]);
        if(isset($kbx_res['msg'])){
            return $kbx_res['msg'];
        }elseif(!isset($kbx_res['_id'])){
            Log::write("更新订单状态失败，返回结果：".json_encode($kbx_res));
            return "修改状态失败";
        }else{
            //修改订单系统状态成功
            //更新定制系统状态
            Db::name('trip')->where(['id'=>$trip['id']])->update(['isPaid'=>1]);
            Db::name('custom_made_order')->where(['id'=>$order['id']])->update(['order_status'=>2]);

            return $kbx_res;
        }
    }
    
    //模拟信用卡生成返回数据
    public function myPayByCredit()
    {
        return json_decode('{
	"id": "ch_1FOL6IKmCl4AInt0ok1cAAw9",
	"object": "charge",
	"amount": 288800,
	"amount_refunded": 0,
	"application": null,
	"application_fee": null,
	"application_fee_amount": null,
	"balance_transaction": "txn_1FOL6IKmCl4AInt0bJjgQkIO",
	"billing_details": {
		"address": {
			"city": null,
			"country": null,
			"line1": null,
			"line2": null,
			"postal_code": null,
			"state": null
		},
		"email": null,
		"name": null,
		"phone": null
	},
	"captured": true,
	"created": 1569835406,
	"currency": "cny",
	"customer": null,
	"description": "快帮行-电商平台-订单：STF52978-【ToB测试自营商品】自由女神和爱丽丝岛之旅-信用卡支付：CNY 2888",
	"destination": null,
	"dispute": null,
	"failure_code": null,
	"failure_message": null,
	"fraud_details": [],
	"invoice": null,
	"livemode": false,
	"metadata": {
		"project": "STF52978"
	},
	"on_behalf_of": null,
	"order": null,
	"outcome": {
		"network_status": "approved_by_network",
		"reason": null,
		"risk_level": "normal",
		"risk_score": 45,
		"seller_message": "Payment complete.",
		"type": "authorized"
	},
	"paid": true,
	"payment_intent": null,
	"payment_method": "card_1FOL6HKmCl4AInt0w3pT1yIn",
	"payment_method_details": {
		"card": {
			"brand": "visa",
			"checks": {
				"address_line1_check": null,
				"address_postal_code_check": null,
				"cvc_check": "pass"
			},
			"country": "US",
			"exp_month": 4,
			"exp_year": 2024,
			"fingerprint": "x8GEQw69zBpEg0Dp",
			"funding": "credit",
			"last4": "4242",
			"three_d_secure": null,
			"wallet": null
		},
		"type": "card"
	},
	"receipt_email": null,
	"receipt_number": null,
	"receipt_url": "https:\/\/pay.stripe.com\/receipts\/acct_19w2LEKmCl4AInt0\/ch_1FOL6IKmCl4AInt0ok1cAAw9\/rcpt_Fu9PL8vT95iLsPqzBldV34BTiMK5lBS",
	"refunded": false,
	"refunds": {
		"object": "list",
		"data": [],
		"has_more": false,
		"total_count": 0,
		"url": "\/v1\/charges\/ch_1FOL6IKmCl4AInt0ok1cAAw9\/refunds"
	},
	"review": null,
	"shipping": null,
	"source": {
		"id": "card_1FOL6HKmCl4AInt0w3pT1yIn",
		"object": "card",
		"address_city": null,
		"address_country": null,
		"address_line1": null,
		"address_line1_check": null,
		"address_line2": null,
		"address_state": null,
		"address_zip": null,
		"address_zip_check": null,
		"brand": "Visa",
		"country": "US",
		"customer": null,
		"cvc_check": "pass",
		"dynamic_last4": null,
		"exp_month": 4,
		"exp_year": 2024,
		"fingerprint": "x8GEQw69zBpEg0Dp",
		"funding": "credit",
		"last4": "4242",
		"metadata": [],
		"name": null,
		"tokenization_method": null
	},
	"source_transfer": null,
	"statement_descriptor": "kuaibangxing.com",
	"statement_descriptor_suffix": null,
	"status": "succeeded",
	"transfer_data": null,
	"transfer_group": null
}',true);

    }
}

